// 订单自主查询系统 - 全局JavaScript文件

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 表单验证
    initFormValidation();
    
    // 平滑滚动
    initSmoothScroll();
    
    // 加载状态处理
    initLoader();
    
    // 移动端菜单
    initMobileMenu();
    
    // 表单提交拦截
    initFormSubmit();
    
    // 提示框自动关闭
    initAutoDismissAlerts();
    
    // 修复移动端表单点击问题
    fixMobileFormClick();
});

/**
 * 初始化表单验证
 */
function initFormValidation() {
    const forms = document.querySelectorAll('form.needs-validation');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!form.checkValidity()) {
                e.preventDefault();
                e.stopPropagation();
            }
            
            form.classList.add('was-validated');
        }, false);
    });
}

/**
 * 初始化平滑滚动
 */
function initSmoothScroll() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            if (targetId === '#') return;
            
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                targetElement.scrollIntoView({
                    behavior: 'smooth'
                });
            }
        });
    });
}

/**
 * 初始化加载状态处理
 */
function initLoader() {
    const loaders = document.querySelectorAll('.loader');
    const formSubmits = document.querySelectorAll('form button[type="submit"]');
    
    formSubmits.forEach(button => {
        button.addEventListener('click', function() {
            const form = this.closest('form');
            const loader = form.querySelector('.loader');
            
            if (loader && form.checkValidity()) {
                loader.style.display = 'block';
                button.disabled = true;
                button.textContent = '处理中...';
            }
        });
    });
}

/**
 * 初始化移动端菜单
 */
function initMobileMenu() {
    const menuToggle = document.querySelector('.mobile-menu-toggle');
    const mobileMenu = document.querySelector('.mobile-menu');
    
    if (menuToggle && mobileMenu) {
        menuToggle.addEventListener('click', function() {
            mobileMenu.classList.toggle('show');
        });
    }
}

/**
 * 初始化表单提交处理
 */
function initFormSubmit() {
    // 只针对后台特定表单使用AJAX提交，不拦截前台表单
    const adminForms = document.querySelectorAll('form.ajax-submit');
    
    adminForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            submitFormAjax(this.action, formData);
        });
    });
}

/**
 * 修复移动端表单点击问题 - 增强版
 */
function fixMobileFormClick() {
    // 为所有设备添加增强的点击支持，不局限于移动设备检测
    // 避免设备检测不准确导致的问题
    
    // 为所有按钮和可点击元素添加增强的点击支持
    const clickableElements = document.querySelectorAll('button, a, input[type="submit"], input[type="button"], .result-card');
    clickableElements.forEach(element => {
        // 确保元素可以被点击
        element.style.pointerEvents = 'auto';
        
        // 为可点击元素添加视觉反馈
        if (!element.classList.contains('no-hover')) {
            element.style.transition = 'background-color 0.2s, transform 0.1s';
        }
        
        // 为按钮和卡片添加触摸事件支持
        if (element.tagName === 'BUTTON' || element.tagName === 'A' || element.classList.contains('result-card')) {
            // 移除可能存在的冲突事件监听器
            const newElement = element.cloneNode(true);
            if (element.parentNode) {
                element.parentNode.replaceChild(newElement, element);
                
                // 为新元素添加触摸和点击事件
                newElement.addEventListener('touchstart', function(e) {
                    // 避免与点击事件冲突
                    e.stopPropagation();
                    // 添加触摸视觉反馈
                    this.style.transform = 'scale(0.98)';
                }, { passive: false });
                
                newElement.addEventListener('touchend', function(e) {
                    e.stopPropagation();
                    this.style.transform = '';
                }, { passive: false });
                
                newElement.addEventListener('touchmove', function(e) {
                    e.stopPropagation();
                    this.style.transform = '';
                }, { passive: true });
            }
        }
    });
    
    // 为前台查询表单添加特殊处理
    const searchForm = document.querySelector('.search-form');
    if (searchForm) {
        // 确保表单可以正常提交
        searchForm.style.pointerEvents = 'auto';
        searchForm.style.zIndex = '10';
        
        // 为搜索按钮添加增强的触摸事件支持
        const searchButton = document.getElementById('searchButton');
        if (searchButton) {
            searchButton.addEventListener('touchstart', function(e) {
                e.preventDefault();
                this.style.backgroundColor = 'rgba(59, 130, 246, 0.9)';
            }, { passive: false });
            
            searchButton.addEventListener('touchend', function(e) {
                e.preventDefault();
                this.style.backgroundColor = '';
                // 使用延时确保视觉反馈生效后再触发点击
                setTimeout(() => this.click(), 50);
            }, { passive: false });
        }
    }
}

/**
 * AJAX表单提交
 * @param {string} url - 提交URL
 * @param {FormData} formData - 表单数据
 */
function submitFormAjax(url, formData) {
    const xhr = new XMLHttpRequest();
    const loader = document.querySelector('.loader');
    const messageContainer = document.querySelector('.message-container');
    
    if (loader) {
        loader.style.display = 'block';
    }
    
    xhr.open('POST', url, true);
    xhr.onload = function() {
        if (loader) {
            loader.style.display = 'none';
        }
        
        if (xhr.status === 200) {
            try {
                const response = JSON.parse(xhr.responseText);
                
                if (response.success) {
                    showMessage('success', response.message || '操作成功！');
                    if (response.redirect) {
                        setTimeout(() => {
                            window.location.href = response.redirect;
                        }, 1500);
                    }
                } else {
                    showMessage('error', response.message || '操作失败！');
                }
            } catch (e) {
                showMessage('error', '服务器响应格式错误');
            }
        } else {
            showMessage('error', '服务器错误，请稍后重试');
        }
    };
    
    xhr.onerror = function() {
        if (loader) {
            loader.style.display = 'none';
        }
        showMessage('error', '网络错误，请检查您的网络连接');
    };
    
    xhr.send(formData);
}

/**
 * 显示提示消息
 * @param {string} type - 消息类型 success/error/info/warning
 * @param {string} message - 消息内容
 */
function showMessage(type, message) {
    const messageContainer = document.querySelector('.message-container');
    
    if (!messageContainer) {
        return;
    }
    
    const messageElement = document.createElement('div');
    messageElement.className = `message message-${type}`;
    messageElement.textContent = message;
    
    messageContainer.innerHTML = '';
    messageContainer.appendChild(messageElement);
    messageContainer.style.display = 'block';
    
    // 3秒后自动隐藏
    setTimeout(() => {
        messageElement.style.opacity = '0';
        messageElement.style.transition = 'opacity 0.5s ease';
        
        setTimeout(() => {
            messageContainer.style.display = 'none';
        }, 500);
    }, 3000);
}

/**
 * 初始化自动关闭的提示框
 */
function initAutoDismissAlerts() {
    const alerts = document.querySelectorAll('.alert-auto-dismiss');
    
    alerts.forEach(alert => {
        setTimeout(() => {
            alert.style.opacity = '0';
            alert.style.transition = 'opacity 0.5s ease';
            
            setTimeout(() => {
                alert.style.display = 'none';
            }, 500);
        }, 3000);
    });
}

/**
 * 显示加载指示器
 */
function showLoader() {
    const loader = document.createElement('div');
    loader.className = 'loader';
    loader.id = 'global-loader';
    loader.innerHTML = `
        <div class="loader-spinner"></div>
        <div class="loader-text">加载中...</div>
    `;
    
    document.body.appendChild(loader);
}

/**
 * 隐藏加载指示器
 */
function hideLoader() {
    const loader = document.getElementById('global-loader');
    if (loader) {
        loader.remove();
    }
}

/**
 * 设置Cookie
 * @param {string} name - Cookie名称
 * @param {string} value - Cookie值
 * @param {number} days - 过期天数
 */
function setCookie(name, value, days) {
    let expires = '';
    if (days) {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = '; expires=' + date.toUTCString();
    }
    document.cookie = name + '=' + (value || '')  + expires + '; path=/';
}

/**
 * 获取Cookie
 * @param {string} name - Cookie名称
 * @returns {string|null} Cookie值
 */
function getCookie(name) {
    const nameEQ = name + '=';
    const ca = document.cookie.split(';');
    for(let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

/**
 * 删除Cookie
 * @param {string} name - Cookie名称
 */
function deleteCookie(name) {
    document.cookie = name + '=; Max-Age=-99999999;';
}

/**
 * 检查是否为移动设备
 * @returns {boolean} 是否为移动设备
 */
function isMobile() {
    return window.innerWidth <= 768;
}

/**
 * 复制文本到剪贴板
 * @param {string} text - 要复制的文本
 * @returns {Promise} 复制结果
 */
function copyToClipboard(text) {
    if (navigator.clipboard && window.isSecureContext) {
        return navigator.clipboard.writeText(text);
    } else {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        return new Promise((resolve, reject) => {
            try {
                const result = document.execCommand('copy');
                document.body.removeChild(textArea);
                result ? resolve() : reject(new Error('复制失败'));
            } catch (error) {
                document.body.removeChild(textArea);
                reject(error);
            }
        });
    }
}